package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.GetDomainNameReq;
import net.ib.mntalk.protocol.Session.GetDomainNameRes;
import net.ib.mtalk.network.MethodId;
import net.ib.mtalk.network.TcpClient;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;

public class GetDomainNameTask extends AsyncNetTask {

	public GetDomainNameTask(Context context) {
		super(context);
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		GetDomainNameReq req = new GetDomainNameReq();

		TcpEnvelope envelope = new TcpEnvelope.Builder()
		.setType(TcpEnvelope.REQUEST)
		.setMethodId(MethodId.Session.Server.GetDomainName)
		.setMessage(req)
		.build();

		return envelope;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject, Object receivedObject) {
		if (receivedObject == null) {
			return;
		}

		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		GetDomainNameRes getDomainNameRes = (GetDomainNameRes) resultEnvelope.getMessage();
		
		if (getDomainNameRes.getResponseCode() == Common.SUCCESS) {
			if (! getDomainNameRes.hasDomainName()) {
				MTalkLogWriter.w("GetDomainNameTask.onPostExecute(): received empty domain name");
				return;
			}
			MTalkLogWriter.d("GetDomainNameTask.onPostExecute(): saved new domain name="+getDomainNameRes.getDomainName());
			TcpClient.setDomain(getDomainNameRes.getDomainName());	// 새로 받은 도메인을 저장한다.
		} else {
			MTalkLogWriter.w("GetDomainNameTask.onPostExecute(): req fail");
		}

	}

}
